package com.example.piece.ui.adapter

import android.Manifest
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.text.Editable
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.View
import android.widget.*
import androidx.annotation.RequiresApi
import androidx.appcompat.widget.AppCompatEditText
import androidx.constraintlayout.widget.ConstraintSet
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.chad.library.adapter.base.BaseProviderMultiAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.example.base.aop.click.RepeatClick
import com.example.base.aop.login.LoginCallback
import com.example.base.aop.permission.PermissionRequest
import com.example.base.broadcast.Event
import com.example.base.broadcast.EventBusUtil
import com.example.base.ext.*
import com.example.base.popup.util.KeyboardUtils
import com.example.base.tools.ConfigTool
import com.example.base.tools.JsonTool
import com.example.base.tools.MsgImageTarget
import com.example.base.ui.activity.BaseActivity
import com.example.base.vm.onError
import com.example.piece.App
import com.example.piece.R
import com.example.piece.constant.Key
import com.example.piece.constant.RoutePath
import com.example.piece.databinding.ItemHomeRecommendationPhotoBinding
import com.example.piece.databinding.ItemHomeRecommendationTextBinding
import com.example.piece.databinding.ItemHomeRecommendationVideoBinding
import com.example.piece.entity.AttentionEntity
import com.example.piece.tools.SIMCardInfo
import com.example.piece.vm.JokesViewModel
import com.example.piece.vm.UserViewModel
import com.kongzue.dialogx.dialogs.BottomDialog
import com.kongzue.dialogx.dialogs.FullScreenDialog
import com.kongzue.dialogx.interfaces.DialogLifecycleCallback
import com.kongzue.dialogx.interfaces.OnBindView
import com.wenming.library.encryption.imp.AESEncode
import com.example.piece.BR
import com.example.piece.tools.ShareUtil
import com.github.iielse.imageviewer.core.MyPhotoData
import com.example.piece.vm.HelperViewModel
import com.github.iielse.imageviewer.ImageViewerBuilder
import com.github.iielse.imageviewer.core.SimpleDataProvider
import com.example.piece.tools.SimpleImageLoader
import com.example.piece.tools.SimpleTransformer
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kongzue.dialogx.interfaces.OnBackPressedListener
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import kotlin.properties.Delegates


class HomeRecommendationAdapter() : BaseProviderMultiAdapter<AttentionEntity>(), LoadMoreModule {
    lateinit var userViewModel: UserViewModel
    lateinit var jokesViewModel: JokesViewModel
    lateinit var helperViewModel: HelperViewModel

    lateinit var fragment: BaseActivity<ViewDataBinding>
    var isRemove by Delegates.notNull<Boolean>()

    constructor(
        data: List<AttentionEntity>,
        userViewModel: UserViewModel,
        jokesViewModel: JokesViewModel,
        helperViewModel: HelperViewModel,
        fragment: BaseActivity<ViewDataBinding>,
        isJump: Boolean = true,
        isRemove: Boolean = false,
    ) : this() {
        this.userViewModel = userViewModel
        this.jokesViewModel = jokesViewModel
        this.helperViewModel = helperViewModel

        this.fragment = fragment
        this.isRemove = isRemove
        addItemProvider(TextItemProvider(userViewModel, jokesViewModel, fragment, this))
        addItemProvider(ImgItemProvider(userViewModel, jokesViewModel, fragment, this))

        addItemProvider(VideoItemProvider(userViewModel, jokesViewModel, fragment, this))
        if (isJump) {
            setOnItemClickListener(object : OnItemClickListener {
                override fun onItemClick(
                    adapter: BaseQuickAdapter<*, *>,
                    view: View,
                    position: Int,
                ) {
                    fragment.navigationTo(RoutePath.MAIN_DETAIL_ACTIVITY, mutableMapOf(
                        Key.DataKey.H5_TITLE to "帖子详情",
                        Key.DataKey.ITEM_DETAIL to JsonTool.object2Json(adapter.data[position]))

                    )
                }

            })
        }


    }

    override fun getItemType(data: List<AttentionEntity>, position: Int): Int {
        return when (data[position].joke.type) {
            "1" -> {
                AttentionEntity.TEXT
            }
            "2" -> {
                AttentionEntity.IMG
            }
            else -> {
                AttentionEntity.Video
            }

        }

    }

    @RepeatClick
    fun clickShare(item: AttentionEntity) {
        BottomDialog.build()
            .setCustomView(object : OnBindView<BottomDialog>(R.layout.dialog_share) {
                override fun onBind(dialog: BottomDialog?, v: View?) {
                    v?.findViewById<ImageView>(R.id.img_wx)?.setOnClickListener { //微信
                        context?.let { it1 -> ShareUtil.shareTextToWechat(it1, "测试") }

                    }
                    v?.findViewById<ImageView>(R.id.img_pyq)?.setOnClickListener { //朋友圈
                        getphoto()

                    }
                    v?.findViewById<ImageView>(R.id.img_qq)?.setOnClickListener { //QQ
                        context?.let { it1 -> ShareUtil.shareTextToQQFriend(it1, "测试") }

                    }
                    v?.findViewById<ImageView>(R.id.img_zone)?.setOnClickListener { //空间

                    }
                    v?.findViewById<ImageView>(R.id.img_vb)?.setOnClickListener { //微博
                        context?.let { it1 -> ShareUtil.shareTextToVB(it1, "测试") }

                    }
                    v?.findViewById<ImageView>(R.id.img_shoucang)?.setOnClickListener { //收藏
                        //首先判断是否收藏

                        jokesViewModel.jokesIsCollect(fragment, item.joke.jokesId) {
                            if (it.code == 200) {

                                jokesViewModel.jokesCollect(fragment,
                                    item.joke.jokesId,
                                    (!it.data.is_collect).toString()) { it1 ->
                                    if (it1.code == 200) {
                                        if (it.data.is_collect) {//取消成功 移除
                                            if (isRemove) {
                                                remove(item)

                                            }
                                            EventBusUtil.sendEvent(Event(Key.EventKey.EVENT_USERINFO_SC,
                                                -1L))
                                        } else {
                                            EventBusUtil.sendEvent(Event(Key.EventKey.EVENT_USERINFO_SC,
                                                1L))
                                        }
                                        dialog?.dismiss()

                                    } else {
                                        fragment.toast(it.msg)

                                    }
                                    fragment.toast(it1.msg)
                                } onError {
                                    fragment.toast(it)

                                }
                            } else {
                                fragment.toast(it.msg)

                            }
                        } onError {
                            fragment.toast(it)

                        }


                    }
                    v?.findViewById<ImageView>(R.id.img_copy)?.setOnClickListener { //复制
                        helperViewModel.helperJokeShare(fragment, item.joke.jokesId) {
                            if (it.code == 200) {
                                val entity = it.data
                                setClipboardContent(entity.share_title + "\n" + entity.share_content + "\n" + entity.share_url + "\n" + entity.share_img)
                                dialog?.dismiss()
                                fragment.toast("复制成功")

                            } else {
                                fragment.toast(it.msg)

                            }
                        } onError {
                            fragment.toast(it)


                        }
                    }
                    v?.findViewById<ImageView>(R.id.img_jb)?.setOnClickListener { //举报
                        navigationTo(RoutePath.MAIN_JUBAO_ACTIVITY)
                        dialog?.dismiss()

                    }
                    v?.findViewById<ImageView>(R.id.img_xq)?.setOnClickListener { //详情
                        fragment.navigationTo(RoutePath.MAIN_DETAIL_ACTIVITY, mutableMapOf(
                            Key.DataKey.H5_TITLE to "帖子详情",
                            Key.DataKey.ITEM_DETAIL to JsonTool.object2Json(item))

                        )

                        dialog?.dismiss()
                    }
                }

            })
            .show()
    }


    /**  点击添加图片的事件  **/
    @PermissionRequest(
        value = [
            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
        ]
    )
    private fun getphoto() {
        context?.let { it1 ->
            //要在子线程中使用，否则会报错
            val dataUri = ArrayList<Uri>()
            val dataDeferred = ArrayList<Deferred<Int>>()

            var waitId = 0;
            var progress = 0F
            WaitDialog.show("正在加载", WaitDialog.TYPE.NONE).setOnBackPressedListener(object :
                OnBackPressedListener {
                override fun onBackPressed(): Boolean {
                    MessageDialog.show("正在进行", "是否取消？", "是", "否")
                        .setOkButton(object : OnDialogButtonClickListener<MessageDialog> {
                            override fun onClick(baseDialog: MessageDialog, v: View?): Boolean {

                                waitId = -1
                                WaitDialog.dismiss()
                                return false
                            }


                        })
                    return false
                }

            })

            runBlocking {
                val data = ArrayList<String>()
                data.add("https://tva1.sinaimg.cn/large/0080xEK2ly1gftvfumyb7g30a80gge83.gif")
                data.add("http://wx2.sinaimg.cn/large/9bd522c1ly1gfg6zsy960g206s0aahe1.gif")
                data.add("http://wx4.sinaimg.cn/large/5eef6257gy1g8qmhbxeslg207s0dqx74.gif")
                data.add("http://juheimg.oss-cn-hangzhou.aliyuncs.com/joke/201602/19/32E90AB13A4841D3E1FC6233CED69B20.gif")
                data.add("http://wx4.sinaimg.cn/large/5eef6257gy1g8ttfjvbffg20690b4qv5.gif")
                data.add("https://gif.55.la/static/keyword/images/img2.gif")
                data.add("https://gif.55.la/static/keyword/images/img1.gif")
                data.add("https://gif.55.la/static/keyword/images/img4.gif")
                data.add("https://gif.55.la/static/keyword/images/img6.gif")
                for (i in 0 until 9) {

                    val c1 = async(Dispatchers.IO) {
                        Glide.with(it1)
                            .asBitmap()
                            .load(data.get(i))
                            .into(object : SimpleTarget<Bitmap>() {
                                override fun onResourceReady(
                                    resource: Bitmap,
                                    transition: Transition<in Bitmap>?,
                                ) {
                                    val uri = resource.saveToGallery(context!!, resource)
                                    if (uri != null) {
                                        dataUri.add(uri)
                                    }

                                    progress = (dataUri.size / data.size.toFloat())
                                    WaitDialog.show("正在加载" + ((progress * 100).toInt()).toString() + "%",
                                        progress)
                                    if (progress == 1f) {
                                        WaitDialog.dismiss()
                                        //  TipDialog.show(activity,"加载完成", WaitDialog.TYPE.SUCCESS,2000)
                                        if (dataUri.size > 0) {
                                            context?.let {
                                                ShareUtil.sharePictureToWechatUri(it, dataUri, "")
                                                Log.e("TAG", "getFXData: .2222")
                                            }

                                        }
                                    } else {


                                    }
                                    Log.e("TAG", "getFXData: ." + dataUri.size)
                                }


                            })
                        1
                    }
                    dataDeferred.add(c1)

                }
                for (it in dataDeferred) {
                    it.await()
                }
            }


        }
    }
    @LoginCallback
    @RepeatClick
    fun clickLike(
        item: AttentionEntity,
        helper: BaseViewHolder,
    ) {
       /* if (App.USER_TOKEN.isNullOrEmpty()) {//未登录
            gotoLogin()
        } else {*/
            jokesViewModel.jokesLike(fragment,
                item.joke.jokesId,
                (!item.info.isLike).toString()) {
                if (it.code == 200) {
                    item.info.isLike = !item.info.isLike
                    if (item.info.isLike) {
                        item.info.likeNum = item.info.likeNum + 1
                    } else {
                        item.info.likeNum = item.info.likeNum - 1
                    }


                    notifyItemChanged(helper.layoutPosition, 0)


                }else{
                    fragment.toast(it.msg)

                }
            } onError {

            }
       // }
    }
    @LoginCallback
    @RepeatClick
    fun clickCai(
        item: AttentionEntity,
        helper: BaseViewHolder,
    ) {
       /* if (App.USER_TOKEN.isNullOrEmpty()) {//未登录
            gotoLogin()
        } else {*/
            jokesViewModel.jokesUnlike(fragment,
                item.joke.jokesId,
                (!item.info.isUnlike).toString()) {
                if (it.code == 200) {
                    item.info.isUnlike = !item.info.isUnlike
                    if (item.info.isUnlike) {
                        item.info.disLikeNum = item.info.disLikeNum + 1
                    } else {
                        item.info.disLikeNum = item.info.disLikeNum - 1
                    }


                    notifyItemChanged(helper.layoutPosition, 1)
                }else{
                    fragment.toast(it.msg)

                }
            } onError {
                fragment.toast(it)

            }
    //    }
    }

    @RepeatClick
    fun goToPL(item: AttentionEntity) {
        BottomDialog.build()
            .setCustomView(object : OnBindView<BottomDialog>(R.layout.dialog_pinglun) {
                override fun onBind(dialog: BottomDialog?, v: View?) {
                    val rvPl = v?.findViewById<RecyclerView>(R.id.rv_pl)
                    v?.findViewById<ImageView>(R.id.img_close)?.setOnClickListener {
                        dialog?.dismiss()

                    }


                    val pingLunNodeAdapter =
                        PingLunNodeAdapter(userViewModel, jokesViewModel, fragment)
                    rvPl?.adapter = pingLunNodeAdapter
                    pingLunNodeAdapter.setEmptyView(R.layout.layout_empty)
                    var page = 1

                    pingLunNodeAdapter.loadMoreModule.isAutoLoadMore = true
                    pingLunNodeAdapter.loadMoreModule.isEnableLoadMoreIfNotFullPage = true
                    pingLunNodeAdapter.loadMoreModule.setOnLoadMoreListener {
                        page++
                        getPLList(item, page, pingLunNodeAdapter)

                    }

                    getPLList(item, page, pingLunNodeAdapter)
                    v?.findViewById<LinearLayout>(R.id.ll_pl)?.setOnClickListener {

                      /*  if (App.USER_TOKEN.isNullOrEmpty()) {//未登录
                            gotoLogin()
                        } else {*/
                            BottomDialog.show(object :
                                OnBindView<BottomDialog>(R.layout.dialog_pinglun_write) {
                                override fun onBind(dialog: BottomDialog?, v: View?) {
                                    val etPL = v?.findViewById<AppCompatEditText>(R.id.et_pl)
                                    etPL?.postDelayed({ KeyboardUtils.open(etPL) }, 100)
                                    val imgSend = v?.findViewById<ImageView>(R.id.img_send)
                                    etPL?.addTextChangedListener(object : TextWatcher {
                                        override fun beforeTextChanged(
                                            s: CharSequence?,
                                            start: Int,
                                            count: Int,
                                            after: Int,
                                        ) {
                                        }

                                        override fun onTextChanged(
                                            s: CharSequence?,
                                            start: Int,
                                            before: Int,
                                            count: Int,
                                        ) {
                                            imgSend?.isSelected = !s.isNullOrEmpty()
                                        }

                                        override fun afterTextChanged(s: Editable?) {

                                        }
                                    })

                                    imgSend?.setOnClickListener {
                                        if (!etPL?.text.toString().isNullOrEmpty()) {//提交评论
                                            jokesViewModel.jokesComment(fragment,
                                                item.joke.jokesId,
                                                etPL?.text.toString()) {
                                                if (it.code == 200) {
                                                    val data = it.data
                                                    pingLunNodeAdapter.addData(listOf(data))
                                                    dialog?.dismiss()
                                                }else{
                                                    fragment.toast(it.msg)

                                                }

                                            } onError {
                                                fragment.toast(it)

                                            }
                                        }

                                    }


                                }

                            }).isAllowInterceptTouch = false
                        }

                    }
               // }

            })
            .show()
    }

    private fun getPLList(
        item: AttentionEntity,
        page: Int,
        pingLunNodeAdapter: PingLunNodeAdapter,
    ) {
        jokesViewModel.jokesCommentList(fragment, item.joke.jokesId, page.toString()) {
            if (it.code == 200) {
                if (it.data.comments.isNullOrEmpty()) {
                    pingLunNodeAdapter.loadMoreModule.isEnableLoadMore = false
                    pingLunNodeAdapter.loadMoreModule.isAutoLoadMore = false
                    return@jokesCommentList
                }
                if (page === 1) {
                    pingLunNodeAdapter.setList(it.data.comments)

                } else {
                    pingLunNodeAdapter.addData(it.data.comments)

                }
            }else{
                fragment.toast(it.msg)

            }
        } onError {
            fragment.toast(it)

        }
    }

    private fun gotoLogin() {
        val onBindView =
            object :
                OnBindView<FullScreenDialog>(R.layout.layout_full_login, true) {
                @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
                override fun onBind(dialog: FullScreenDialog?, v: View?) {
                    val tvPhone = v?.findViewById<EditText>(R.id.edit_userName)
                    v?.findViewById<TextView>(R.id.tv_getCode)//获取验证码
                        ?.setOnClickListener {
                            if (!tvPhone?.text.isNullOrEmpty()) {
                                userViewModel.userLoginGetCode(
                                    fragment,
                                    tvPhone?.text.toString()
                                ) {
                                    fragment.toast(it.msg)
                                } onError {
                                    fragment.toast(it)

                                }
                            } else {
                                fragment.toast("请输入手机号码！")
                            }

                        }
                    v?.findViewById<TextView>(R.id.tv_loginByOwenPhone)
                        ?.setOnClickListener {
                            getOwnPhone(tvPhone)
                        }

                    val etPsd = v?.findViewById<TextView>(R.id.edit_password)

                    v?.findViewById<ImageView>(R.id.img_qq)
                        ?.setOnClickListener {
                            if (!tvPhone?.text.isNullOrEmpty()) {
                                userViewModel.userPswReset(
                                    fragment,
                                    etPsd?.text.toString(), "111sam111",
                                    tvPhone?.text.toString()
                                ) {
                                    fragment.toast(it.msg)
                                } onError {
                                    fragment.toast(it)

                                }
                            } else {
                                fragment.toast("请输入手机号码！")
                            }
                        }
                    v?.findViewById<TextView>(R.id.btn_submit)
                        ?.setOnClickListener {
                            if (!tvPhone?.text.isNullOrEmpty()) {
                                if (!etPsd?.text.isNullOrEmpty()) {
                                    userViewModel.userLoginCode(
                                        fragment,
                                        etPsd?.text.toString(),
                                        tvPhone?.text.toString()
                                    ) {
                                        if (it.code === 200) {
                                            App.USER_TOKEN = it.data.token
                                            //存本地token
                                            ConfigTool.putString(Key.DataKey.TOKEN, it.data.token)
                                            //登录成功
                                            EventBusUtil.sendEvent(Event<Int>(Key.EventKey.EVENT_LOGIN))
                                            dialog?.dismiss()
                                        }
                                    } onError {
                                        fragment.toast(it)

                                    }
                                } else {
                                    fragment.toast("请输入验证码！")

                                }

                            } else {
                                fragment.toast("请输入手机号码！")
                            }
                        }


                    val spannableStringBuilder = SpannableStringBuilder()
                    //设置文字
                    spannableStringBuilder.append("登录/注册代表您同意《用户服务条款》\n和《隐私协议》")
                    //设置文字点击事件（用户协议）
                    spannableStringBuilder.setSpan(object : ClickableSpan() {
                        override fun onClick(widget: View) {
                            navigationTo(
                                RoutePath.MAIN_H5_ACTIVITY, mutableMapOf(
                                    Key.DataKey.H5_TITLE to "用户协议",

                                    Key.DataKey.H5_URL to "https://res.villaday.com/static/pages/1907/19/190717-19.html"
                                )
                            )
                        }
                    }, 10, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

                    //设置文字点击事件（隐私协议）
                    spannableStringBuilder.setSpan(object : ClickableSpan() {
                        override fun onClick(widget: View) {
                            navigationTo(
                                RoutePath.MAIN_H5_ACTIVITY, mutableMapOf(
                                    Key.DataKey.H5_TITLE to "隐私协议",
                                    Key.DataKey.H5_URL to "https://res.villaday.com/static/pages/1907/19/190717-19.html"
                                )
                            )
                        }
                    }, 20, 26, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                    //设置颜色
                    spannableStringBuilder.setSpan(
                        ForegroundColorSpan(
                            Color.parseColor(
                                "#46AFFF"
                            )
                        ), 10, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                    spannableStringBuilder.setSpan(
                        ForegroundColorSpan(
                            Color.parseColor(
                                "#46AFFF"
                            )
                        ), 20, 26, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                    )


                    val tvXieYi = v?.findViewById<TextView>(R.id.tv_xieyi)
                    tvXieYi?.movementMethod = LinkMovementMethod.getInstance()
                    tvXieYi?.text = spannableStringBuilder

                }

            }
        FullScreenDialog.show(onBindView).dialogLifecycleCallback = object :
            DialogLifecycleCallback<FullScreenDialog>() {
            override fun onDismiss(dialog: FullScreenDialog?) {
                super.onDismiss(dialog)

            }

            override fun onShow(dialog: FullScreenDialog?) {
                super.onShow(dialog)
            }

        }
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
    fun getOwnPhone(phone: TextView?) {
        val phoneNumbers =
            fragment?.let { SIMCardInfo(it).phoneNumberS }
        if (phoneNumbers?.isNotEmpty() == true) {
            for (it in phoneNumbers) {

            }
            phone?.text = phoneNumbers[0]

        } else {
            fragment.toast("暂未获取到手机号")
        }


    }


}

class TextItemProvider : BaseItemProvider<AttentionEntity> {

    private val userViewModel: UserViewModel
    private val jokesViewModel: JokesViewModel
    private val fragment: BaseActivity<ViewDataBinding>
    private val homeRecommendationAdapter: HomeRecommendationAdapter

    constructor(
        userViewModel: UserViewModel,
        jokesViewModel: JokesViewModel,
        fragment: BaseActivity<ViewDataBinding>,
        homeRecommendationAdapter: HomeRecommendationAdapter,
    ) : super() {
        this.userViewModel = userViewModel
        this.jokesViewModel = jokesViewModel
        this.fragment = fragment
        this.homeRecommendationAdapter = homeRecommendationAdapter
    }

    override val itemViewType: Int = AttentionEntity.TEXT
    override val layoutId: Int = R.layout.item_home_recommendation_text

    /**
     * 当 ViewHolder 创建完毕以后，会执行此回掉
     * 可以在这里做任何你想做的事情
     */
    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        // 绑定View
        DataBindingUtil.bind<ItemHomeRecommendationTextBinding>(viewHolder.itemView)
    }

    override fun convert(helper: BaseViewHolder, item: AttentionEntity) {
        val binding =

            DataBindingUtil.getBinding<ItemHomeRecommendationTextBinding>(helper.itemView)

        val variable = binding?.setVariable(BR.entity, item)
        binding?.setVariable(BR.adapter, this)
        binding?.setVariable(BR.position, helper.layoutPosition)
        binding?.imgHead?.setCircleCropImageUrl(item?.user?.avatar)
        binding?.imgLike?.isSelected = item.info.isLike
        binding?.imgUnlike?.isSelected = item.info.isUnlike


        //喜欢
        binding?.imgLike?.setOnClickListener {
            homeRecommendationAdapter.clickLike(item, helper)
        }
        //踩
        binding?.imgUnlike?.setOnClickListener {
            homeRecommendationAdapter.clickCai(item, helper)
        } //评论
        binding?.imgPl?.setOnClickListener {
            homeRecommendationAdapter.goToPL(item)
        }
        //分享
        binding?.imgShare?.setOnClickListener {
            homeRecommendationAdapter.clickShare(item)
        }
        binding?.executePendingBindings()
    }

    override fun convert(helper: BaseViewHolder, item: AttentionEntity, payloads: List<Any>) {
        super.convert(helper, item, payloads)
        val binding =
            DataBindingUtil.getBinding<ItemHomeRecommendationTextBinding>(helper.itemView)
        when (payloads.get(0)) {
            0 -> {
                binding?.imgLike?.isSelected = item.info.isLike
                binding?.tvLike?.text = item.info.likeNum.toString()
            }//更新喜欢

            1 -> {
                binding?.imgUnlike?.isSelected = item.info.isUnlike
                binding?.tvUnlike?.text = item.info.disLikeNum.toString()

            }//更新踩
        }

    }
    @LoginCallback
    fun onGuanZhu(position: Int) {
    /*    if (App.USER_TOKEN.isNullOrEmpty()) {
            fragment.toast("请登录")
        } else {
*/
            getAdapter()?.data?.get(position)?.user?.userId?.let {
                userViewModel.userAttention(fragment, "1", it) {
                    if (it.code == 200) {
                        getAdapter()?.data?.get(position)?.info?.isAttention = true
                        getAdapter()?.notifyDataSetChanged()
                    } else {
                        fragment.toast(it.msg)
                    }
                } onError {
                    fragment.toast(it)

                }
            }
       // }
    }

    @RepeatClick
    fun onJuBao(position: Int) {
        BottomDialog.build()
            .setCustomView(object : OnBindView<BottomDialog>(R.layout.dialog_jubao_for_item) {
                override fun onBind(dialog: BottomDialog?, v: View?) {
                    v?.findViewById<TextView>(R.id.tv_jubao)?.setOnClickListener { //举报

                        navigationTo(RoutePath.MAIN_JUBAO_ACTIVITY)
                        dialog?.dismiss()
                    }
                    v?.findViewById<TextView>(R.id.tv_cancel)?.setOnClickListener { //取消
                        dialog?.dismiss()
                    }
                }

            })
            .show()
    }
}

class ImgItemProvider : BaseItemProvider<AttentionEntity> {
    private val userViewModel: UserViewModel
    private val jokesViewModel: JokesViewModel
    private val fragment: BaseActivity<ViewDataBinding>
    private val homeRecommendationAdapter: HomeRecommendationAdapter

    constructor(
        userViewModel: UserViewModel,
        jokesViewModel: JokesViewModel,
        fragment: BaseActivity<ViewDataBinding>,
        homeRecommendationAdapter: HomeRecommendationAdapter,
    ) : super() {
        this.userViewModel = userViewModel
        this.jokesViewModel = jokesViewModel
        this.fragment = fragment
        this.homeRecommendationAdapter = homeRecommendationAdapter


    }

    override val itemViewType: Int = AttentionEntity.IMG
    override val layoutId: Int = R.layout.item_home_recommendation_photo

    /**
     * 当 ViewHolder 创建完毕以后，会执行此回掉
     * 可以在这里做任何你想做的事情
     */
    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        // 绑定View
        DataBindingUtil.bind<ItemHomeRecommendationPhotoBinding>(viewHolder.itemView)
    }

    override fun convert(helper: BaseViewHolder, item: AttentionEntity) {
        val binding =
            DataBindingUtil.getBinding<ItemHomeRecommendationPhotoBinding>(helper.itemView)
        val variable = binding?.setVariable(BR.entity, item)
        binding?.setVariable(BR.adapter, this)
        binding?.setVariable(BR.position, helper.layoutPosition)
        binding?.imgHead?.setCircleCropImageUrl(item?.user?.avatar)
        val splitWH = item.joke.imageSize?.split(",")
        if (splitWH != null && splitWH.isNotEmpty()) {
            val split = splitWH[0].split("x")
            if (split.size > 1) {
                val srcWidth = split[0].toInt()
                val srcHeight = split[1].toInt()
                var params: LinearLayout.LayoutParams? = null
                if (srcWidth > srcHeight) {
                    val srcWHRatio = srcWidth / srcHeight
                    // 宽图
                    if (srcWHRatio > MsgImageTarget.RATIO_OF_LARGE) {
                        params = LinearLayout.LayoutParams(
                            srcHeight * MsgImageTarget.HW_RATIO,
                            srcHeight
                        )

                    } else {
                        params = LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            context.screenWidth * srcHeight / srcWidth
                        )

                    }
                } else {
                    val srcHWRatio = srcHeight / srcWidth
                    //长图
                    if (srcHWRatio > MsgImageTarget.RATIO_OF_LARGE) {
                        params =
                            LinearLayout.LayoutParams(srcWidth, srcWidth * MsgImageTarget.HW_RATIO)


                    } else {
                        params = LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            context.screenWidth * srcHeight / srcWidth
                        )

                    }
                }
                binding?.imgContent?.layoutParams = params
            }

        } else {
            var params: LinearLayout.LayoutParams? = null

            params = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )

            binding?.imgContent?.layoutParams = params

        }



        Log.e("ddddddddddddd", item?.joke?.imageUrl?.replace("ftp://", "").toString().trim())
        val imgUrl =
            AESEncode.Decrypt(
                item?.joke?.imageUrl?.split(",")?.get(0)?.replace("ftp://", "").toString().trim(),
                "cretinzp**273846"
            )


        Log.e("ddddddddddddd", imgUrl + "")

        if (imgUrl.contains(".gif")) {//是GIF图片
            binding?.imgContent?.setGifImageUrl(imgUrl, 2)

        } else {
            binding?.imgContent?.setBigAndLongImageUrl(imgUrl, 10)


        }
        binding?.imgLike?.isSelected = item.info.isLike
        binding?.imgUnlike?.isSelected = item.info.isUnlike


        //喜欢
        binding?.imgLike?.setOnClickListener {
            homeRecommendationAdapter.clickLike(item, helper)
        }
        //踩
        binding?.imgUnlike?.setOnClickListener {
            homeRecommendationAdapter.clickCai(item, helper)
        } //评论
        binding?.imgPl?.setOnClickListener {
            homeRecommendationAdapter.goToPL(item)
        }
        //分享
        binding?.imgShare?.setOnClickListener {
            homeRecommendationAdapter.clickShare(item)
        }

        binding?.executePendingBindings()
    }


    override fun convert(helper: BaseViewHolder, item: AttentionEntity, payloads: List<Any>) {
        super.convert(helper, item, payloads)
        val binding =
            DataBindingUtil.getBinding<ItemHomeRecommendationPhotoBinding>(helper.itemView)
        when (payloads.get(0)) {
            0 -> {
                binding?.imgLike?.isSelected = item.info.isLike
                binding?.tvLike?.text = item.info.likeNum.toString()
            }//更新喜欢

            1 -> {
                binding?.imgUnlike?.isSelected = item.info.isUnlike
                binding?.tvUnlike?.text = item.info.disLikeNum.toString()

            }//更新踩
        }

    }
    @LoginCallback
    fun onGuanZhu(position: Int) {
       /* if (App.USER_TOKEN.isNullOrEmpty()) {
            fragment.toast("请登录")
        } else {*/

            getAdapter()?.data?.get(position)?.user?.userId?.let {
                userViewModel.userAttention(fragment, "1", it) {
                    if (it.code == 200) {
                        getAdapter()?.data?.get(position)?.info?.isAttention = true
                        getAdapter()?.notifyDataSetChanged()
                    } else {
                        fragment.toast(it.msg)
                    }
                } onError {
                    fragment.toast(it)

                }
            }
       // }
    }

    @RepeatClick
    fun onJuBao(position: Int) {
        BottomDialog.build()
            .setCustomView(object : OnBindView<BottomDialog>(R.layout.dialog_jubao_for_item) {
                override fun onBind(dialog: BottomDialog?, v: View?) {
                    v?.findViewById<TextView>(R.id.tv_jubao)?.setOnClickListener { //举报

                        navigationTo(RoutePath.MAIN_JUBAO_ACTIVITY)
                        dialog?.dismiss()
                    }
                    v?.findViewById<TextView>(R.id.tv_cancel)?.setOnClickListener { //取消
                        dialog?.dismiss()
                    }
                }

            })
            .show()
    }

    @RepeatClick
    fun onPhoto(position: Int) {
        val dataList = arrayListOf<MyPhotoData>()// 将要展示的图片集合列表
        val item = getAdapter()?.data?.get(position)

        for ((index,it ) in item?.joke?.imageUrl?.split(",")?.withIndex()!!) {
            val imgUrl =
                AESEncode.Decrypt(
                    it?.replace("ftp://", "").toString().trim(),
                    "cretinzp**273846"
                )
            dataList.add(MyPhotoData(index.toLong(),imgUrl))

        }



        val builder = ImageViewerBuilder(
            context = context,
            dataProvider = SimpleDataProvider(dataList), // 一次性全量加载 // 实现DataProvider接口支持分页加载
            imageLoader = SimpleImageLoader(), // 可使用demo固定写法 // 实现对数据源的加载.支持自定义加载数据类型，加载方案
            transformer = SimpleTransformer(), // 可使用demo固定写法 // 以photoId为标示，设置过渡动画的'配对'.
        )
        builder.show()


    }
}

class VideoItemProvider : BaseItemProvider<AttentionEntity> {
    private val userViewModel: UserViewModel
    private val jokesViewModel: JokesViewModel
    private val fragment: BaseActivity<ViewDataBinding>
    private val homeRecommendationAdapter: HomeRecommendationAdapter

    constructor(
        userViewModel: UserViewModel,
        jokesViewModel: JokesViewModel,
        fragment: BaseActivity<ViewDataBinding>,
        homeRecommendationAdapter: HomeRecommendationAdapter,
    ) : super() {
        this.userViewModel = userViewModel
        this.jokesViewModel = jokesViewModel
        this.fragment = fragment
        this.homeRecommendationAdapter = homeRecommendationAdapter

    }

    override val itemViewType: Int = AttentionEntity.Video
    override val layoutId: Int = R.layout.item_home_recommendation_video

    /**
     * 当 ViewHolder 创建完毕以后，会执行此回掉
     * 可以在这里做任何你想做的事情
     */
    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        // 绑定View
        DataBindingUtil.bind<ItemHomeRecommendationVideoBinding>(viewHolder.itemView)
    }

    override fun convert(helper: BaseViewHolder, item: AttentionEntity) {
        val binding =
            DataBindingUtil.getBinding<ItemHomeRecommendationVideoBinding>(helper.itemView)
        val variable = binding?.setVariable(BR.entity, item)
        binding?.setVariable(BR.adapter, this)
        binding?.setVariable(BR.position, helper.layoutPosition)
        binding?.imgHead?.setCircleCropImageUrl(item?.user?.avatar)
        val prepareView = binding?.prepareView
        prepareView?.setOnClickListener {
            getAdapter()?.setOnItemChildClick(prepareView, helper.layoutPosition)
        }

        val clt = binding?.clt

        val splitWH = item.joke.videoSize?.split(",")
        if (splitWH != null) {
            if (splitWH.size > 1) {
                val srcWidth = splitWH[0].toInt()
                val srcHeight = splitWH[1].toInt()

                val constraintSet = ConstraintSet()
                constraintSet.clone(clt)
                if (srcWidth / srcHeight < 4 / 3) {
                    constraintSet.setDimensionRatio(R.id.player_container, "h,4:3")

                } else {
                    constraintSet.setDimensionRatio(R.id.player_container, "h,$srcWidth:$srcHeight")

                }
                constraintSet.applyTo(clt)

            } else {
                var params: FrameLayout.LayoutParams? = null
                params = FrameLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                )
                prepareView?.layoutParams = params

            }
        }


        val mThumb = prepareView?.findViewById<ImageView>(R.id.thumb)
        Log.e("ddddddddddddd", item?.joke?.thumbUrl?.replace("ftp://", "").toString().trim())
        val mThumbUrl =
            AESEncode.Decrypt(
                item?.joke?.thumbUrl?.split(",")?.get(0)?.replace("ftp://", "").toString().trim(),
                "cretinzp**273846"
            )

        mThumb?.getContext()?.let {
            Glide.with(it)
                .load(mThumbUrl)
                .placeholder(android.R.color.darker_gray)
                .into(mThumb)
        }
        binding?.imgLike?.isSelected = item.info.isLike
        binding?.imgUnlike?.isSelected = item.info.isUnlike

        //喜欢
        binding?.imgLike?.setOnClickListener {
            homeRecommendationAdapter.clickLike(item, helper)
        }
        //踩
        binding?.imgUnlike?.setOnClickListener {
            homeRecommendationAdapter.clickCai(item, helper)
        } //评论
        binding?.imgPl?.setOnClickListener {
            homeRecommendationAdapter.goToPL(item)
        }
        //分享
        binding?.imgShare?.setOnClickListener {
            homeRecommendationAdapter.clickShare(item)
        }
        binding?.executePendingBindings()
    }

    override fun convert(helper: BaseViewHolder, item: AttentionEntity, payloads: List<Any>) {
        super.convert(helper, item, payloads)
        val binding =
            DataBindingUtil.getBinding<ItemHomeRecommendationVideoBinding>(helper.itemView)
        when (payloads.get(0)) {
            0 -> {
                binding?.imgLike?.isSelected = item.info.isLike
                binding?.tvLike?.text = item.info.likeNum.toString()
            }//更新喜欢

            1 -> {
                binding?.imgUnlike?.isSelected = item.info.isUnlike
                binding?.tvUnlike?.text = item.info.disLikeNum.toString()

            }//更新踩
        }

    }
    @LoginCallback
    fun onGuanZhu(position: Int) {
      /*  if (App.USER_TOKEN.isNullOrEmpty()) {
            fragment.toast("请登录")
        } else {
*/
            getAdapter()?.data?.get(position)?.user?.userId?.let {
                userViewModel.userAttention(fragment, "1", it) {
                    if (it.code == 200) {
                        getAdapter()?.data?.get(position)?.info?.isAttention = true
                        getAdapter()?.notifyDataSetChanged()
                    } else {
                        fragment.toast(it.msg)
                    }
                } onError {
                    fragment.toast(it)

                }
            }
       // }
    }

    @RepeatClick
    fun onJuBao(position: Int) {
        BottomDialog.build()
            .setCustomView(object : OnBindView<BottomDialog>(R.layout.dialog_jubao_for_item) {
                override fun onBind(dialog: BottomDialog?, v: View?) {
                    v?.findViewById<TextView>(R.id.tv_jubao)?.setOnClickListener { //举报

                        navigationTo(RoutePath.MAIN_JUBAO_ACTIVITY)
                        dialog?.dismiss()
                    }
                    v?.findViewById<TextView>(R.id.tv_cancel)?.setOnClickListener { //取消
                        dialog?.dismiss()
                    }
                }

            })
            .show()
    }


}
